import { Redirect, useModel } from 'umi';
import { useEffect } from 'react';
import { message } from 'antd';
import { loginService } from '@/service';
import { executeActionAfterReq } from '@/util/errorHandle';

export default (props: any) => {
  const { teacher, setTeacher } = useModel('useTeacher');
  const authorization = sessionStorage.getItem('Authorization');
  const csrfToken = document.cookie.split('; ')?.pop()?.split('=')[1];

  useEffect(() => {
    getTokenInfo();
  }, [teacher]);

  const getTokenInfo = async () => {
    if (csrfToken && authorization && !teacher) {
      const res = await loginService.getTokenInfo().catch(() => {
        message.error('请求错误');
      });
      executeActionAfterReq(res, () => {
        setTeacher(res?.data);
      })
    }
  }

  if (!authorization || !csrfToken) {
    message.error('请先登录');
    return <Redirect to="/index/login" />;
  } else if (teacher?.tType === 1) { // 实验员
    if (props.route.tType === 0) {
      message.error('无权限');
      props.history.goBack();
    }
    return <div>{ props.children }</div>;
  } else { // 实验室管理人员
    return <div>{ props.children }</div>;
  } 
}
